package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.KMDMTBoxAdapter;
import com.example.administrator.yanfoxconn.adapter.LCMainUpCheckAdapter;
import com.example.administrator.yanfoxconn.adapter.ZhiyinshuiCheckAdapter;
import com.example.administrator.yanfoxconn.bean.LCMessage;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.bean.ZhiyinshuiCheckMsg;
import com.example.administrator.yanfoxconn.bean.ZhiyinshuiMsg;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.EditTextWithScrollView;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.example.administrator.yanfoxconn.widget.TouchImageView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 營建-現場勘查記錄提交界面
 * @Author song
 * @Date 12/22/21 7:46 PM
 */
public class LCMainUpActivity extends BaseActivity implements View.OnClickListener {
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_SET_ITEM = 7;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息
    private final int MESSAGE_JUMP = 4;//跳轉維護界面
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_INFO = 6;
    private List<LCMessage> itemList,zdList,hsList,infoList;//基本信息
    private LCMainUpCheckAdapter lcItemAdapter;
//    private List<ZhiyinshuiCheckMsg> mCheckMsgList;//點檢項
//    private ZhiyinshuiCheckAdapter mZhiyinshuiCheckAdapter;//點檢列表適配器
    private HashMap<Integer, String> isSelected = new HashMap<>();//用户存储条目的选择状态
    private List<Integer> selectList;//用于存放正常的条目
    private List<Integer> noselectList;//用于存放異常的条目
    private String flag;

    private Map<String,String> checkList= new HashMap<String,String>();;
    private KMDMTBoxAdapter adapter;
    private int key1 = 0;//提交時管控未填寫信息

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_up)
    Button btnUp;//保存

    @BindView(R.id.tv_position)
    TextView tvPosition;//定位
    @BindView(R.id.tv_people)
    TextView tvPeople;//接單人
    @BindView(R.id.tv_date)
    TextView tvDate;//時間
    @BindView(R.id.lv_zhongdian)
    RecyclerView lvZD;//重大項目列表
    @BindView(R.id.et_normal)
    EditTextWithScrollView etNormal;//一般項目
    @BindView(R.id.tr_old_check)
    TableRow trOldCheck;//舊會審
    @BindView(R.id.old_check)
    TextView tvOldCheck;//舊會審
    @BindView(R.id.lv_check)
    MyListView lvCheck;//項目會審
    @BindView(R.id.gl_get_image)
    GridLayout glShowPhoto;//图片占位

    @BindView(R.id.iv_empty)
    ImageView ivEmpty;//空白图片占位
    @BindView(R.id.gv_photo)
    GridView gvPhoto;//图片显示区域

    private String initStartDateTime,initStartDateTime1; // 初始化开始时间
    private Date selectTime = null;//所選時間
    private Date curDate = null;//當前時間
    private String curDates;//當前時間
    private SimpleDateFormat formatter;
    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;

    private ArrayList<String> imagePaths = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPaths = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapter;
    private String gcc01="",audits="";//工程案號，項目會審
    int finalI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lc_up_main);
        ButterKnife.bind(this);

        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        initStartDateTime = formatterUse.format(curDate);
        tvDate.setText(formatter.format(curDate));

        tvTitle.setText("現場勘查記錄");
        btnUp.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        gcc01 = getIntent().getStringExtra("gcc01");
        flag=getIntent().getStringExtra("flag");
        if (flag.equals("N")){
            getZDItem();
        }else{
            getInfo(gcc01);
        }
        ivEmpty.setOnClickListener(this);
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 4 ? 4 : cols;
        gvPhoto.setNumColumns(cols);

        // preview
        gvPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePaths.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(LCMainUpActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(4); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态

                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(LCMainUpActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_up:
                aboutAlert(getResources().getString(R.string.update_confirm),MESSAGE_UP);
                break;
            case R.id.iv_empty:
                PhotoPickerIntent intent = new PhotoPickerIntent(LCMainUpActivity.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(4); // 最多选择照片数量，默认为4
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态

                startActivityForResult(intent, REQUEST_CAMERA_CODE);
                break;
        }
    }

    private void getZDItem(){
        showDialog();
        final String url = Constants.HTTP_LC_CONSTRUCT_KEY_POINT ;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                Log.e("---------", "==fff===" + url);
                dismissDialog();
                if (result != null) {
                    Gson gson = new Gson();
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();

                        itemList = new ArrayList<LCMessage>();

                            for (JsonElement type : array) {
                                LCMessage humi = gson.fromJson(type, LCMessage.class);
                                itemList.add(humi);
                            }

                            Message message = new Message();
                            message.what = MESSAGE_SET_ITEM;
                            message.obj = jsonObject.get("msg").getAsString();
                            mHandler.sendMessage(message);

                        Log.e("---------", "result==fff===" + result);
                    } else{
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("msg").getAsString();
                        mHandler.sendMessage(message);
                    }
                }else{
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            } }.start();
    }
    private void getInfo(String gcc01){
        showDialog();
        final String url = Constants.HTTP_LC_CONSTRUCT_INFO+"?gcc01="+gcc01 ;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                Log.e("---------", "==fff===" + url);
                dismissDialog();
                if (result != null) {
                    Gson gson = new Gson();
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();


                        infoList = new ArrayList<LCMessage>();

                        for (JsonElement type : array) {
                            LCMessage humi = gson.fromJson(type, LCMessage.class);
                            infoList.add(humi);
                        }

                        Message message = new Message();
                        message.what = MESSAGE_SET_INFO;
                        message.obj = jsonObject.get("msg").getAsString();
                        mHandler.sendMessage(message);

                        Log.e("---------", "result==fff===" + result);
                    } else{
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("msg").getAsString();
                        mHandler.sendMessage(message);
                    }
                }else{
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            } }.start();
    }

//    private void getCheckMessage(){
//        showDialog();
//        final String url = Constants.HTTP_WATER_INFO_SERVLET +"?flag=S&dim_id="+dim_id+"&type="+type;
//        new Thread() {
//            @Override
//            public void run() {
//                //把网络访问的代码放在这里
//                String result = HttpUtils.queryStringForPost(url);
//                Log.e("---------", "==fff===" + url);
//                dismissDialog();
//                Gson gson = new Gson();
//                if (result != null) {
//                    Log.e("---------", "result==fff===" + result);
//                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
//                    String errCode = jsonObject.get("errCode").getAsString();
//                    if (errCode.equals("200")) {
//                        JsonArray array = jsonObject.get("result").getAsJsonArray();
//                        mCheckMsgList = new ArrayList<ZhiyinshuiCheckMsg>();
//                        for (JsonElement type : array) {
//                            ZhiyinshuiCheckMsg humi = gson.fromJson(type, ZhiyinshuiCheckMsg.class);
//                            mCheckMsgList.add(humi);
//                        }
//
//                        Message message = new Message();
//                        message.what = MESSAGE_SET_CHECK;
//                        message.obj = jsonObject.get("errMessage").getAsString();
//                        mHandler.sendMessage(message);
//
//                    } else{
//                        Message message = new Message();
//                        message.what = MESSAGE_TOAST;
//                        message.obj = jsonObject.get("errMessage").getAsString();
//                        mHandler.sendMessage(message);
//                    }
//                }else{
//                    Message message = new Message();
//                    message.what = MESSAGE_NETMISTAKE;
//                    mHandler.sendMessage(message);
//                    finish();
//                }
//            } }.start();
//    }
    //提交前檢查
    private void check() {

        final String url = Constants.HTTP_LC_CONSTRUCT_POST_RECORD; //此處寫上自己的URL

        JsonObject object = new JsonObject();
        HashMap<Integer, String> etMap;//存放editText值的map
        HashMap<Integer, String> etCheckMap;//存放editText值的map
        BDLocation location = FoxContext.getInstance().getLocation();
        if (location == null || location.getLongitude() == 0.0 || location.getLatitude() == 0.0) {
            ToastUtils.showLong(this, "位置信息獲取失敗請稍後或移動后重試!");
        }
        etMap = LCMainUpCheckAdapter.getEtMap();
        JsonArray array = new JsonArray();
        JsonArray photoArray = new JsonArray();

        if (checkList != null && checkList.size() != 0) {
            // 键和值
            String key = null;
            String value = null;
            // 获取键值对的迭代器
            Iterator it = checkList.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                value = (String) entry.getValue();
                key=(String) entry.getKey();
                JsonObject jsonObject1 = new JsonObject();
                Log.e("------","dddcheckList=="+checkList.size()+"==dddkey=="+key);
                if (audits.equals("")){
                    audits=key;
                }else{
                    audits=audits+","+key;
                }
            }

        } else {
        }
        object.addProperty("gcc01", gcc01);
        object.addProperty("position", tvPosition.getText().toString());
        object.addProperty("audit", audits);
        object.addProperty("weihu_name", FoxContext.getInstance().getName());
        object.addProperty("weihu_date", tvDate.getText().toString());

        selectList = new ArrayList<>();
        noselectList = new ArrayList<>();
        //清除之前选择的数据
        selectList.clear();//選項true
        noselectList.clear();//選項false
        //遍历map集合
        for (int key : isSelected.keySet()) {
            //Log.e("-----------", "isSelected.get(key)===" + isSelected.get(key));
            //判断是否已选择，如果已选择，则添加进selectList
            if (isSelected.get(key).equals("true")) {
                selectList.add(key);
            } else if(isSelected.get(key).equals("false")){
                noselectList.add(key);
            } 
        }
//        Log.e("----------", "selectList" + selectList.toString());
//        Log.e("----------", "noselectList" + noselectList.toString());
//        Log.e("----------", "inputTureList" + inputTureList.toString());
//        Log.e("----------", "inputFalseList" + inputFalseList.toString());
//        Log.e("----------", "selectTureList" + selectTureList.toString());
//        Log.e("----------", "selectFalseList" + selectFalseList.toString());

//        for (int i = 0; i < selectList.size(); i++) {
//            int j = selectList.get(i);
//            JsonObject jsonObject = new JsonObject();
//            jsonObject.addProperty("id", mCheckMsgList.get(j).getId());
//            jsonObject.addProperty("desp", "");
//
//            if (mCheckMsgList.get(j).getOption().get(0).getFlag().equals("0")){//正常
//                jsonObject.addProperty("result", mCheckMsgList.get(j).getOption().get(0).getOpt());
//            }else {//異常
//                jsonObject.addProperty("result", mCheckMsgList.get(j).getOption().get(1).getOpt());
//            }
//            jsonObject.addProperty("opt_flag", 0);
//            JsonArray photoArray = new JsonArray();
//            jsonObject.add("photo", photoArray);
//            array.add(jsonObject);
//        }

        for (int i = 0; i < noselectList.size(); i++) {
            int j = noselectList.get(i);
            if (etMap.get(j) == null || etMap.get(j).equals("")) {
                key1++;
                //Log.e("-----------", "key1-----" + key1);
            }
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("type", "ZD");
            jsonObject.addProperty("keypoint", itemList.get(j).getPoint_name());
            jsonObject.addProperty("record", etMap.get(j));
            array.add(jsonObject);
        }
        JsonObject jsonObject2 = new JsonObject();
        jsonObject2.addProperty("type", "YB");
        jsonObject2.addProperty("keypoint", "一般項目");
        jsonObject2.addProperty("record", etNormal.getText().toString());
        array.add(jsonObject2);

        object.add("items", array);

if (imagePaths!=null) {
    for (int i = 0; i < imagePaths.size(); i++) {
        File pictureFile = new File(imagePaths.get(i)); //通過路徑獲取檔
//            fileMap.put("file" + i, pictureFile);//添加第一個文件
        final String pic_path = imagePaths.get(i);
        String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
        String _path = sign_dir + File.separator + System.currentTimeMillis() + i + ".jpg";
        //getFilesDir().getAbsolutePath()+"compressPic.jpg";
        //调用压缩图片的方法，返回压缩后的图片path
        final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 50);
        String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("item", "" + (i + 1));
        jsonObject.addProperty("image", picBase64Code);
        photoArray.add(jsonObject);
    }
    if (flag.equals("Y")&&infoList.get(0).getPhotoList().size()>0){
        for (int i=0;i<infoList.get(0).getPhotoList().size();i++){
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("item", "" + (i + 1));
            jsonObject.addProperty("image", infoList.get(0).getPhotoList().get(i).getImage());
            photoArray.add(jsonObject);
        }
    }
    object.add("photoList", photoArray);
}else{
    if (flag.equals("Y")&&infoList.get(0).getPhotoList().size()>0){
        for (int i=0;i<infoList.get(0).getPhotoList().size();i++){
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("item", "" + (i + 1));
            jsonObject.addProperty("image", infoList.get(0).getPhotoList().get(i).getImage());
            photoArray.add(jsonObject);
        }
    }
    object.add("photoList", photoArray);
}
        //Log.e("-----object------",  object.toString());

        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
            return;
        }
        if (key1 > 0) {
            ToastUtils.showShort(this, "請填寫異常信息");
            key1 = 0;
            return;
        }

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("---------", "==fff===" + url);
                    Log.e("---------", "==object===" + object.toString());
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("msg").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(LCMainUpActivity.this);
                }
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MESSAGE_TOAST://Toast彈出
                    aboutAlert(msg.obj.toString(),MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
//                    finish();
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(LCMainUpActivity.this,R.string.net_mistake);
                    break;
                case MESSAGE_SET_TEXT://text賦值
//                    setText();
                    break;
                case MESSAGE_SET_ITEM://text賦值
//                    setText();
                    tvPosition.setText(FoxContext.getInstance().getPosition());
                    tvPeople.setText(FoxContext.getInstance().getName());
                    if (itemList != null) {
                        zdList=new ArrayList<>();
                        hsList=new ArrayList<>();
                        for (int i=0;i<itemList.size();i++){
                            if (itemList.get(i).getFlag().equals("ZD")){
                                zdList.add(itemList.get(i));
                            }else if(itemList.get(i).getFlag().equals("SC")){
                                hsList.add(itemList.get(i));
                            }
                        }
                        LinearLayoutManager layoutManager = new LinearLayoutManager(LCMainUpActivity.this);
                        lvZD.setLayoutManager(layoutManager);
                        lvZD.setItemViewCacheSize(500);
                        if (!flag.equals("N")){
                            lcItemAdapter=new LCMainUpCheckAdapter(LCMainUpActivity.this,zdList,isSelected,infoList.get(0).getItems());
                        }else{

                            lcItemAdapter=new LCMainUpCheckAdapter(LCMainUpActivity.this,zdList,isSelected);
                        }
                    lvZD.setAdapter(lcItemAdapter);
                     } else {
                        ToastUtils.showShort(LCMainUpActivity.this, "沒有數據!");
                    }
                    lvCheck.setVisibility(View.VISIBLE);
                    // 适配
                    adapter = new KMDMTBoxAdapter(hsList, LCMainUpActivity.this,"lc");
                    lvCheck.setAdapter(adapter);

                    setListViewHeightBasedOnChildren(lvCheck);
                    // 绑定listView的监听器
                    lvCheck.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                long arg3) {
                            // TODO Auto-generated method stub
                            // 取得ViewHolder对象
                            KMDMTBoxAdapter.ViewHolder viewHolder = (KMDMTBoxAdapter.ViewHolder) arg1.getTag();
                            // 改变CheckBox的状态
                            viewHolder.checkBox.toggle();
                            // 将CheckBox的选中状况记录下来
                            hsList.get(arg2).setBo(viewHolder.checkBox.isChecked());

                            // 调整选定条目
                            if (viewHolder.checkBox.isChecked() == true) {
                                Log.e("---------","checkList=checkList.size()+"+checkList.size()+"+=="+hsList.get(arg2).getPoint_name());
//                    pric += Integer.parseInt(list.get(arg2).getName());
                                checkList.put(hsList.get(arg2).getPoint_name(),hsList.get(arg2).getPoint_name());
                                ;
                            } else {

//                    pric -= Integer.parseInt(list.get(arg2).getName());
                                checkList.remove(hsList.get(arg2).getPoint_name());
                            }}
                    });
                    break;
//                case MESSAGE_UP://提交響應
//                    worningAlert(msg.obj.toString(),MESSAGE_TOAST);
////                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
//                    break;
//                case MESSAGE_SET_CHECK://點檢項列表賦值
//
//                    if (mCheckMsgList != null) {
//                        LinearLayoutManager layoutManager = new LinearLayoutManager(LCMainUpActivity.this);
//                        rvOption.setLayoutManager(layoutManager);
//                        rvOption.setItemViewCacheSize(500);
//                        mZhiyinshuiCheckAdapter = new ZhiyinshuiCheckAdapter(LCMainUpActivity.this,mCheckMsgList,isSelected);
//                        rvOption.setAdapter(mZhiyinshuiCheckAdapter);
//                    } else {
//                        ToastUtils.showShort(LCMainUpActivity.this, "沒有數據!");
//                    }
//                    break;

                case MESSAGE_SET_INFO://跳轉維護異常界面
                    trOldCheck.setVisibility(View.VISIBLE);
                    tvOldCheck.setText(infoList.get(0).getAudit());
                    showPhoto();
                    getZDItem();
                    break;
            }
            super.handleMessage(msg);
        }
    };



    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==MESSAGE_TOAST){
                            finish();
                        }else if(type==MESSAGE_UP){

                            check();
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
//                        if (type==MESSAGE_TOAST){
//                            finish();
//                        }else if(type==MESSAGE_UP){
//                            check();
//                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

//    private void worningAlert(String msg, final int t) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("提示信息")
//                .setMessage(msg)
//                .setCancelable(false)
//                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int id) {
//                        // TODO Auto-generated method stub
//                        if (t==MESSAGE_TOAST){
//                            finish();
//                        }else if (t==MESSAGE_JUMP){
//                            Intent intent = new Intent(LCMainUpActivity.this, ZhiyinshuiExceListActivity.class);
//                            intent.putExtra("dim_id",dim_id);
//                            intent.putExtra("type",type);
//                            startActivity(intent);
//                            finish();
//                            ToastUtils.showShort(LCMainUpActivity.this, "跳轉異常界面!");
//                        }
//                    }
//                });
//        AlertDialog alert = builder.create();
//        alert.show();
//    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths);
                        Log.e("==========", paths.get(1));
                    }
                    break;

            }
        } else {
            switch (resultCode) {
                case 33:
                    Log.e("==========", "canYinSecondAdapter.notifyDataSetChanged();===");
                    infoList.get(0).getPhotoList().remove(finalI);
                    Log.e("==========", "canYinSecondAdapter.notifyDataSetChanged();===");
                   // lcItemAdapter.notifyDataSetChanged();
                    showPhoto();
                    break;
                case 44:

                    break;
            }

        }

    }

    /*
    * xia顯示圖片
    * */
    private void showPhoto(){
        glShowPhoto.removeAllViews();
        if (infoList.get(0).getPhotoList().size()>0) {
            glShowPhoto.setVisibility(View.VISIBLE);

//            Log.e("------imgStr0-----", "======" + showPhoto.get(position).get(0));
            if (infoList.get(0).getPhotoList().size()!=0){
                for (int i = 0; i < infoList.get(0).getPhotoList().size(); i++) {

                    Log.e("------imgStr-----", "======" + infoList.get(0).getPhotoList().get(i).getImage());
                    TouchImageView imageView = new TouchImageView(LCMainUpActivity.this);
//                        ImageView imageView = new ImageView(ZhiyinshuiExceDetailActivity.this);
                    String imgStr = infoList.get(0).getPhotoList().get(i).getImage();
                    Log.e("------imgStr-----", "======" + imgStr);
                    byte[] decode = Base64.decode(imgStr, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
                    imageView.setAdjustViewBounds(true);
                    imageView.setScaleType(ImageView.ScaleType.CENTER);
                    imageView.setImageBitmap(bitmap);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, 200);
                    layoutParams.setMargins(10, 10, 10, 10);
                    imageView.setLayoutParams(layoutParams);
                    finalI = i;
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            int[] location = new int[2];
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                Rect frame = new Rect();
                                getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                                int statusBarHeight = frame.top;

                                view.getLocationOnScreen(location);
                                location[1] += 0;
                            } else {
                                view.getLocationOnScreen(location);
                            }
                            view.invalidate();
                            int width = view.getWidth();
                            int height = view.getHeight();

                            Intent intent = new Intent(LCMainUpActivity.this, BigImageActivity.class);
                            Bundle b = new Bundle();
                            b.putString(BigImageActivity.QR_IMAGE_URL, infoList.get(0).getPhotoList().get(finalI).getImage());
                            intent.putExtras(b);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_POSITION,333);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_X_TAG, location[0]);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_Y_TAG, location[1]);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_W_TAG, width);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_H_TAG, height);
//                            startActivity(intent);
                            startActivityForResult(intent,0);
//                                        param1=paramInt1;
//                                        param2=paramInt2;
                            overridePendingTransition(0, 0);
//                                        onClickListener.onclick(position, finalI, view);
                        }
                    });
                    glShowPhoto.addView(imageView);
                }}
        }else{
            glShowPhoto.setVisibility(View.GONE);
        }
    }
    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths == null) {
            imagePaths = new ArrayList<>();
        }
        imagePaths.clear();
        imagePaths.addAll(paths);

        if (paths.size() > 0) {
            ivEmpty.setVisibility(View.GONE);
        } else {
            ivEmpty.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePaths);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapter == null) {
            gridAdapter = new GridAdapter(imagePaths);
            gvPhoto.setAdapter(gridAdapter);
            Log.e("----------------", "ddd==" + imagePaths.size());
        } else {
            gridAdapter.notifyDataSetChanged();
        }
    }
    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 3) {
                return 3;
            } else {
                return listUrls.size() + 1;
            }

        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }
            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 3) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(LCMainUpActivity.this)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }
    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        KMDMTBoxAdapter listAdapter = (KMDMTBoxAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LCMainUpCheckAdapter.getEtMap().clear();
//        LCMainUpCheckAdapter.getEtCheckMap().clear();
    }
}